<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()">
      <!-- <el-form-item label="类型：" :label-width="formLabelWidth" prop="classType">
        <el-radio-group v-model="dataForm.classType" :disabled="dataForm.parentId != 0" @change="handleType">
          <el-radio label="1">元器件</el-radio>
          <el-radio label="2">CBB模块</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model.trim="dataForm.name" placeholder="名称"> </el-input>
      </el-form-item>
      <el-form-item label="承运单位" :label-width="formLabelWidth" prop="carrier">
        <el-input v-model.trim="dataForm.carrier" placeholder="承运单位"> </el-input>
      </el-form-item>
      <el-form-item label="收货单位" :label-width="formLabelWidth" prop="consignee">
        <el-input v-model.trim="dataForm.consignee" placeholder="收货单位"> </el-input>
      </el-form-item>
      <el-form-item label="收货方地址" :label-width="formLabelWidth" prop="consigneeAddress">
        <el-input v-model.trim="dataForm.consigneeAddress" type="textarea" placeholder="收货方地址"> </el-input>
      </el-form-item>
      <el-form-item label="收货方联系人及电话" :label-width="formLabelWidth" prop="consigneePhone">
        <el-input v-model.trim="dataForm.consigneePhone" placeholder="收货方联系人及电话"> </el-input>
      </el-form-item>
      <el-form-item label="托运单位" :label-width="formLabelWidth" prop="shipper">
        <el-input v-model.trim="dataForm.shipper" placeholder="托运单位"> </el-input>
      </el-form-item>
      <el-form-item label="托运方联系电话" :label-width="formLabelWidth" prop="shipperPhone">
        <el-input v-model.trim="dataForm.shipperPhone" placeholder="托运方联系电话"> </el-input>
      </el-form-item>
      <el-form-item label="司机信息" :label-width="formLabelWidth" prop="">
        <el-button size="mini" icon="el-icon-plus" type="primary" @click="addDriver()"></el-button>
        <div style="display: flex;margin-bottom: 10px;" v-for="(item, index) in projectDrivers">
          <el-input v-model.trim="item.driverName" placeholder="司机姓名"> </el-input>
          <el-input v-model.trim="item.driverPhone" placeholder="司机联系电话"> </el-input>
          <el-input v-model.trim="item.licenseNumber" placeholder="车牌号"> </el-input>
          <div style="display: flex;margin-left: 10px;align-items: center;">
            <i class="el-icon-remove-outline" style="font-size: 18px;cursor: pointer;margin-right: 5px;"
              @click="deleteDriver(index)"></i>
            <!-- <i class="el-icon-download" style="font-size: 18px;cursor: pointer;" @click="downloadDriver(item.id)"></i> -->
            <!-- <el-button size="mini" icon="el-icon-minus" type="danger" @click="deleteDriver(index)"></el-button>
            <el-button size="mini" icon="el-icon-download" v-if="item.id" @click="downloadDriver(item.id)"></el-button> -->
          </div>
        </div>

      </el-form-item>
      <!-- <el-form-item label="排序号" :label-width="formLabelWidth" prop="orderNum">
				<el-input-number v-model="dataForm.orderNum" :min="0" controls-position="right" label="排序号">
				</el-input-number>
			</el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="dataFormSubmit()" :disabled="isDisabled">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
export default {
  emits: ["refreshDataList"],
  data() {
    let testPhone = (rule, value, callback) => {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (value == '') {
        callback();
      } else if (!reg.test(value)) {
        callback(new Error('手机号格式不正确'));
      } else {
        callback();
      }
    };
    return {

      visible: false,
      dialogFormVisible: false,
      isDisabled: false,
      isval: false,
      isupdate: 0,
      istype: "",
      dataForm: {
        id: 0,
        name: '',//名称
        carrier: '',//承运单位
        consignee: '',//收货单位
        consigneeAddress: '',//收货方地址
        consigneePhone: '',//收货方联系人及电话
        shipper: '',//托运单位
        shipperPhone: '',//托运方联系电话
      },
      projectDrivers: [],
      deltableData: [],
      delAll: [],
      dataRule: {
        name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
        shipperPhone: [
          { validator: testPhone, trigger: 'blur' }
        ],
      },
      validRules: {

      },
      formLabelWidth: "140px",
      visible: false,
      // url: process.env.VUE_APP_BASE_API,
    };
  },
  created() { },
  methods: {
    async init(id) {
      this.dataForm.id = id || 0;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.dataForm.name = "";
        this.delAll = []
        this.projectDrivers = []
        if (!this.dataForm.id) {
          // 新增
          // this.treeListTreeSetCurrentNode()
        } else {
          //获取详情
          this.Sevice({
            url: "/project/info/" + this.dataForm.id,
            method: "get",
          }).then(async (res) => {
            // console.log(res);
            if (res.code != 200) {
              // this.$message.error(res.data.msg)
            } else {
              this.dataForm.id = res.info.id;
              this.dataForm.name = res.info.name;
              this.dataForm.carrier = res.info.carrier;
              this.dataForm.consignee = res.info.consignee;
              this.dataForm.consigneeAddress = res.info.consigneeAddress;
              this.dataForm.consigneePhone = res.info.consigneePhone;
              this.dataForm.shipper = res.info.shipper;
              this.dataForm.shipperPhone = res.info.shipperPhone;
              this.projectDrivers = res.info.projectDrivers
            }
          });
        }
      })

    },
    async insertEvent(row) {
      const $table = this.$refs.xTable
      const record = {
        _XID: uuidv4(),
        driverName: '',
        driverPhone: '',
        licenseNumber: '',
      }
      // const { row: newRow } = await $table.insertAt(record, row)
      // await $table.setActiveCell(newRow, 'name')
      const { row: newRow } = await this.$refs.xTable.insertAt(
        record,
        row
      );
    },
    //司机信息删除
    getRemoveEvent(val, del) {
      if (this[del].length) {
        this.$confirm("您确定要删除该数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then((type) => {
          console.log(type)
          if (type === "confirm") {
            this.$refs[val].removeCheckboxRow();
            //
            for (let i = 0; i < this.deltableData.length; i++) {
              if (this.deltableData[i].id) {
                this.deltableData[i].state = 0
                this.delAll.push(this.deltableData[i])
              }
            }
            this.deltableData = []
            this.projectDrivers = this.$refs[val].afterFullData
            console.log(this.$refs[val].afterFullData)
          }
        }).catch(() => {
        });
      } else {
        this.$message({
          status: "error",
          message: "请先选择需要删除的数据！",
        });
      }
    },
    //全选
    selectAllEvent({ checked, records }) {
      // console.log(checked ? '所有勾选事件' : '所有取消事件', records);
      this.deltableData = records;
    },
    //勾选
    selectChangeEvent({ checked, records }) {
      // console.log(checked ? '勾选事件' : '取消事件', records);
      this.deltableData = records;
    },
    //获取提交数据
    getSubmint() {
      let projectDrivers = []
      // let data = JSON.parse(JSON.stringify(this.$refs.xTable.afterFullData))
      let data = JSON.parse(JSON.stringify(this.projectDrivers))
      projectDrivers = [...this.delAll, ...data]
      return projectDrivers
    },
    addDriver(index) {
      this.projectDrivers.push({
        driverName: '',
        driverPhone: '',
        licenseNumber: '',
      })
    },
    deleteDriver(index) {
      let data = []
      for (let i = 0; i < this.projectDrivers.length; i++) {
        if (i == index) {
          this.projectDrivers[i].state = 0
          this.delAll.push(this.projectDrivers[i])
        } else {
          data.push(this.projectDrivers[i])
        }
      }
      this.projectDrivers = data
    },
    downloadDriver(id) {
      this.Sevice({
        url: '/project/print/' + id,
        method: "post",
        headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
        responseType: 'blob',
        // withCredentials: false,
      }).then((response) => {
        console.log(response);
        let blob = new Blob([response.data], { type: "application/x-msdownload" });
        const fileName =
          decodeURI(response.headers["content-disposition"].split("=")[1]);
        let objectUrl = URL.createObjectURL(blob); // 创建URL
        const link = document.createElement("a");
        link.href = objectUrl;
        // link.download = '.xlsx'// 自定义文件名
        //这里是获取后台传过来的文件名
        link.setAttribute("download", fileName);
        link.click(); // 下载文件
        URL.revokeObjectURL(objectUrl); // 释放内存
      })
        .catch((err) => {
          console.log(err);
        });
    },
    // 表单提交
    async dataFormSubmit() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          // const errMap = await this.$refs.xTable.validate(true).catch((errMap) => errMap);
          // if (errMap) {
          //   this.$message({ status: 'error', message: '校验不通过！' })
          //   return false
          // }
          for (let i = 0; i < this.projectDrivers.length; i++) {
            if (this.projectDrivers[i].driverName == '' && this.projectDrivers[i].driverPhone == '' && this.projectDrivers[i].licenseNumber == '') {
              this.$message({ status: 'error', message: '司机信息未填写完整！' })
              return false
            }
            let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/

            if (this.projectDrivers[i].driverPhone) {
              if (!reg.test(this.projectDrivers[i].driverPhone)) {
                this.$message({ status: 'error', message: '手机号格式不正确!' })
                return false
              }
            }

          }
          let projectDrivers = this.getSubmint()
          let url = this.dataForm.id
            ? "/project/update"
            : "/project/save";
          this.isDisabled = true;
          await this.Sevice({
            url: url,
            method: "post",
            data: {
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              carrier: this.dataForm.carrier,
              consignee: this.dataForm.consignee,
              consigneeAddress: this.dataForm.consigneeAddress,
              consigneePhone: this.dataForm.consigneePhone,
              shipper: this.dataForm.shipper,
              shipperPhone: this.dataForm.shipperPhone,
              projectDrivers: projectDrivers
            },
          }).then((res) => {
            if (res && res.code == 200) {
              this.dialogFormVisible = false;
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.isDisabled = false;
                  this.$emit("getMenuList");
                },
              });
            } else {
              this.isDisabled = false;
            }
          }).catch(error => {
            console.log(error)
            this.isDisabled = false;;
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.mod-menu .menu-list__input>.el-input__inner,
.mod-menu .icon-list__input>.el-input__inner {
  cursor: pointer;
}

.mod-menu__icon-popover {
  width: 458px;
  overflow: hidden;
}

.mod-menu__icon-inner {
  width: 478px;
  max-height: 258px;
  overflow-x: hidden;
  overflow-y: auto;
}

.mod-menu__icon-list {
  width: 458px;
  padding: 0;
  margin: -8px 0 0 -8px;
}

.mod-menu__icon-list>.el-button {
  padding: 8px;
  margin: 8px 0 0 8px;
}

.mod-menu__icon-list>.el-button>span {
  display: inline-block;
  vertical-align: middle;
  width: 18px;
  height: 18px;
  font-size: 18px;
}

.mod-menu .icon-list__tips {
  font-size: 18px;
  text-align: center;
  color: #e6a23c;
  cursor: pointer;
}

.el-tree {
  height: 200px;
  overflow-y: auto;
}
</style>
